<template>
  <div class="py-12">
    <div class="container mx-auto px-4">
      <!-- 页面标题 -->
      <div class="text-center mb-12">
        <h1 class="text-4xl font-bold mb-4">博客文章</h1>
        <p class="text-gray-600 dark:text-gray-400 max-w-2xl mx-auto">
          分享我的技术见解、学习心得和项目开发过程中的经验教训。
        </p>
      </div>

      <!-- 搜索和筛选 -->
      <div
        class="mb-8 flex flex-col md:flex-row justify-between items-center gap-4"
      >
        <div class="relative w-full md:w-64">
          <input
            v-model="searchQuery"
            type="text"
            placeholder="搜索文章..."
            class="w-full px-4 py-2 rounded-md border border-gray-300 dark:border-gray-700 bg-white dark:bg-gray-800 text-gray-800 dark:text-gray-200 focus:outline-none focus:ring-2 focus:ring-primary"
          />
          <i
            class="pi pi-search absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400"
          ></i>
        </div>

        <div
          class="flex flex-wrap gap-2 w-full md:w-auto justify-center md:justify-end"
        >
          <button
            @click="selectedTag = null"
            class="px-3 py-1 rounded-full text-sm font-medium transition-colors duration-300"
            :class="
              selectedTag === null
                ? 'bg-primary text-white'
                : 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600'
            "
          >
            全部
          </button>
          <button
            v-for="tag in uniqueTags"
            :key="tag"
            @click="selectedTag = tag"
            class="px-3 py-1 rounded-full text-sm font-medium transition-colors duration-300"
            :class="
              selectedTag === tag
                ? 'bg-primary text-white'
                : 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600'
            "
          >
            {{ tag }}
          </button>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="isLoading" class="flex justify-center items-center py-20">
        <div
          class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary"
        ></div>
      </div>

      <!-- 文章列表 -->
      <div
        v-else-if="filteredPosts.length > 0"
        class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8"
      >
        <BlogPostCard
          v-for="post in filteredPosts"
          :key="post.id"
          :post="post"
        />
      </div>

      <!-- 无结果提示 -->
      <div v-else class="text-center py-12">
        <i class="pi pi-search text-5xl text-gray-400 mb-4"></i>
        <h3 class="text-xl font-semibold mb-2">未找到相关文章</h3>
        <p class="text-gray-600 dark:text-gray-400">
          尝试使用不同的搜索词或筛选条件。
        </p>
      </div>

      <!-- 分页 -->
      <div v-if="totalPages > 1" class="mt-12 flex justify-center">
        <div class="flex space-x-2">
          <button
            v-for="page in totalPages"
            :key="page"
            @click="currentPage = page"
            class="w-10 h-10 flex items-center justify-center rounded-full transition-colors duration-300"
            :class="
              currentPage === page
                ? 'bg-primary text-white'
                : 'bg-gray-200 dark:bg-gray-700 text-gray-700 dark:text-gray-300 hover:bg-gray-300 dark:hover:bg-gray-600'
            "
          >
            {{ page }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from "vue";
import BlogPostCard from "../components/BlogPostCard.vue";
import { getBlogs, getBlogTags } from "../api/index.ts";

export default {
  name: "BlogView",
  components: {
    BlogPostCard,
  },
  setup() {
    const searchQuery = ref("");
    const selectedTag = ref(null);
    const currentPage = ref(1);
    const postsPerPage = ref(6);
    const isLoading = ref(false);
    const allPosts = ref([]);
    const totalItems = ref(0);
    const availableTags = ref([]);

    // 获取博客文章列表
    const fetchBlogs = async () => {
      isLoading.value = true;
      try {
        const params = {
          page: currentPage.value,
          limit: postsPerPage.value,
          keywords: searchQuery.value,
        };
        const response = await getBlogs(params);
        allPosts.value = response.data.map((post) => ({
          ...post,
          readTime: post.readTime || Math.ceil((post.content?.length || 0) / 1000), // 如果没有阅读时间，根据内容长度估算
        }));
        totalItems.value = response.total;
      } catch (error) {
        console.error("获取博客列表失败:", error);
      } finally {
        isLoading.value = false;
      }
    };

    // 获取博客标签
    const fetchTags = async () => {
      try {
        const response = await getBlogTags();
        availableTags.value = response.tags || [];
      } catch (error) {
        console.error("获取博客标签失败:", error);
      }
    };

    // 初始化数据
    onMounted(() => {
      fetchBlogs();
      fetchTags();
    });

    // 监听搜索、标签和页码变化，重新获取数据
    watch([searchQuery, currentPage], () => {
      fetchBlogs();
    });

    // 当选择标签时，重置页码并更新搜索关键词
    watch(selectedTag, (newTag) => {
      currentPage.value = 1;
      if (newTag) {
        searchQuery.value = newTag;
      } else {
        searchQuery.value = "";
      }
    });

    // 根据搜索和标签筛选文章
    const filteredPosts = computed(() => {
      return allPosts.value;
    });

    // 计算总页数
    const totalPages = computed(() => {
      return Math.ceil(totalItems.value / postsPerPage.value);
    });

    // 提取所有唯一标签
    const uniqueTags = computed(() => {
      return availableTags.value;
    });

    return {
      searchQuery,
      selectedTag,
      currentPage,
      filteredPosts,
      uniqueTags,
      totalPages,
      isLoading,
    };
  },
};
</script>
